<?php

namespace App\Think;

use EasySwoole\ORM\DbManager;
use EasySwoole\Mysqli\QueryBuilder;

use App\Think\Cache;

class Db 
{

    private $alias = null;  //记录全局的语句参数
    private $sql;         //存储最后一条sql
    private $prefix = 'fa_'; //数据表前缀
    private $prefix_cache = 'Db:'; //缓存key前缀
    private static $instance;

    static function init(...$args)
    {
        if(!isset(self::$instance)) self::$instance = new static(...$args);
        return self::$instance;
    }

    //table语句
    static function name( $table )
    {
        // if( !is_string( $table ) ) throw new \exception("table语句的参数必须为字符串");
        // $this->alias['table'] = $this->prefix.$table;
        // return $this;
        // $cls = new self();
        // return $cls->_setTable( $table );

        if(!isset(self::$instance)) self::$instance = new self();
        self::$instance->_setTable( $table );
        return self::$instance;
    }
    //field语句
    public function field( $field )
    {
        if( !is_string( $field ) ) throw new \exception("field语句的参数必须为字符串");
        $this->alias['field'] = $field;
        return $this;
    }
    //转为原生SQL
    static function raw( $string ){
        return "##{$string}##";
    }
    //关联语句
    public function join( $join_table, $on='', $type='LEFT JOIN' ){
        if( !is_string( $join_table ) ) throw new \exception("join_table参数必须为字符串");
        if( !is_string( $on ) ) throw new \exception("on参数必须为字符串");
        $this->alias['join'] = " {$type} {$prefix}{$join_table} ON {$on} ";
        return $this;
    }

    //where语句
    public function where( $where )
    {
        $this->alias['where'] = '';
        if( is_array( $where ) ){
            foreach( $where as $key=>$vo ){
                $this->alias['where'] .= " `$key`" . ' = ' . $vo . ' and ';
            }
            $this->alias['where'] = rtrim( $this->alias['where'], 'and ' );
        }else if( is_string( $where ) ){
            $this->alias['where'] = $where;
        }else{
            throw new \exception("where语句的参数必须为数组或字符串");
        }
        return $this;
    }
    //group语句
    public function group( $group )
    {
        if( !is_string( $group ) ) throw new \exception("group语句的参数必须为字符串");
        $this->alias['group'] = $group;
        return $this;
    }
    //order语句
    public function order( $order )
    {
        if( !is_string( $order ) ) throw new \exception("order语句的参数必须为字符串");
        $this->alias['order'] = $order;
        return $this;
    }
    //limit语句
    public function limit( $limit )
    {
        $this->alias['limit'] = '';
        if( is_numeric( $limit ) ){
           $this->alias['limit'] = '0,' . $limit;
        }else if( is_string( $limit ) ){
            $this->alias['limit'] = $limit;
        }else{
            throw new \exception("limit语句的参数必须为数字或字符串");
        }
        return $this;
    }
    //limit语句
    public function page( $limit )
    {
        $limit_str = explode(',', $limit);
        $page = (isset($limit_str[0]) && $limit_str[0]>0) ? $limit_str[0] : 1;
        $page_size = isset($limit_str[1]) ? $limit_str[1] : 10;

        $this->alias['limit'] = '';
        if( $limit_str ){
            $this->alias['limit'] = ($page-1) . ',' . $page_size;
        }else{
            throw new \exception("limit语句的参数必须为数字或字符串");
        }
        return $this;
    }




    //查询语句
    public function select()
    {
        $this->ParseSelectSql();
        // $res = $this->querySql( $this->sql );
        $res = $this->_setCache($this->sql);
        $result = [];
        $result = isset($res['result']) ? $res['result'] : [];
        return $result;
    }
    //查询一条
    public function find()
    {
        $this->ParseSelectSql();
        $this->sql = str_replace('LIMIT 1', '', $this->sql).' LIMIT 1';
        // $res = $this->querySql( $this->sql );
        $res = $this->_setCache($this->sql);
        return isset($res['result'][0]) ? $res['result'][0] : [];
    }
    //查询一列
    public function column( $field )
    {
        $this->ParseSelectSql();
        // $res = $this->querySql( $this->sql );
        $res = $this->_setCache($this->sql);
        $result = [];
        if(isset($res['result'])) $result = array_column($res['result'], $field);
        return $result;
    }
    //查询一个字段
    public function value( $field )
    {
        $this->ParseSelectSql();
        $this->sql = str_replace('LIMIT 1', '', $this->sql).' LIMIT 1 ';
        // $res = $this->querySql( $this->sql );
        $res = $this->_setCache($this->sql);
        return isset($res['result'][0][$field]) ? $res['result'][0][$field] : [];
    }
    //查询数量
    public function count(){
        $this->ParseSelectSql();
        // $res = $this->querySql( $this->sql );
        $res = $this->_setCache($this->sql);
        if(isset($res['result'][0])){
            $arr  = $res['result'][0];
            $keys = array_keys($arr);
            return count($keys)==1 ? $res['result'][0][$keys[0]] : $res['result'][0];
        }
        return 0;
    }
    //缓存SQL结果
    public function cache($param1, $param2=null){
        if( !is_null($param2) ){ 
            $this->alias['cache_key']     = $param1;
            $this->alias['cache_timeout'] = $param2;
        } else {
            $this->alias['cache_timeout'] = $param1;
        }
        return $this;
    }



    //添加数据
    public function insert( $data )
    {
        if( !is_array( $data ) ) throw new \exception("添加数据add方法参数必须为数组");
        $this->ParseAddSql();
        foreach( $data as $key=>$vo ){
            $this->sql .= " `{$key}` = '" . $vo . "',";
        }
        $res = $this->querySql( rtrim( $this->sql, ',' ) );
        // return $res;
        return isset($res['lastInsertId']) ? $res['lastInsertId'] : 0;
    }
    //添加数据,存在则替换
    public function addReplace( $data, $update_data )
    {
        if( !is_array($data) ) throw new \exception("添加数据addReplace方法参数必须为数组");
        $this->ParseAddSql();
        foreach( $data as $key=>$vo ) $this->sql .= " `{$key}` = '" . $vo . "',";
        $this->sql = rtrim( $this->sql, ',' );

        $this->sql .= ' ON DUPLICATE KEY UPDATE ';
        foreach( $update_data as $key=>$vo ) $this->sql .= " `{$key}` = '" . $vo . "',";
        $this->sql = rtrim( $this->sql, ',' );

        $res = $this->querySql( $this->sql );
        return isset($res['lastInsertId']) ? $res['lastInsertId'] : 0;
    }
    //更新语句
    public function update( $data )
    {
        if( !is_array( $data ) ) throw new \exception("更新数据update方法参数必须为数组");
        $this->ParseUpdateSql();
        foreach( $data as $key=>$vo ){
            $this->sql .= " `{$key}` = '" . $vo . "',";
        }
        $this->sql = rtrim( $this->sql, ',' ) . ' where ' . $this->alias['where'];
        $res = $this->querySql( $this->sql );
        return isset($res['result']) ? $res['result'] : false;
    }
    //更新语句
    public function setInc( $field, $num=1)
    {
        if( !$field ) throw new \exception("请设置需要更新的字段");
        $this->ParseUpdateSql();
        $this->sql .= " `{$field}`=`{$field}`+{$num} ";
        $this->sql = $this->sql . ' where ' . $this->alias['where'];
        $res = $this->querySql( $this->sql );
        return isset($res['result']) ? $res['result'] : false;
    }
    //删除语句
    public function delete()
    {
        $this->ParseDeleteSql();
        $res = $this->querySql( $this->sql );
        return isset($res['result']) ? $res['result'] : false;
    }
    

    //获取查询数据
    public function getData()
    {
        return $this->data;
    }
    //获取最后一次执行的sql语句
    public function getLastSql()
    {
        return $this->sql;
    }


    //事务开始
    static function startTrans(){
        return DbManager::getInstance()->startTransaction('mysql');
    }
    //事务回滚
    static function rollback(){
        return DbManager::getInstance()->rollback('mysql');
    }
    //事务提交
    static function commit(){
        return DbManager::getInstance()->commit('mysql');
    }

    //解析查询sql语句
    public function ParseSelectSql()
    {
        $this->sql = 'select ';
        if( !empty( $this->alias['field'] ) ){
            $this->sql .= $this->alias['field'];//str_replace( '*', $this->alias['field'], $this->sql );
        } else {
            if(!empty($this->alias['count'])){
                $this->sql .= ' count(*) tp_count ';
            } else {
                $this->sql .= ' * ';
            }
        }

        if( empty( $this->alias['table'] ) ){
            throw new \exception("请用table子句设置查询表");
        }else{
            $this->sql .= ' from ' . $this->alias['table'];
        }
        if(!empty($this->alias['join']))  $this->sql .= $this->alias['join'];
        if(!empty($this->alias['where'])) $this->sql .= ' where ' . $this->alias['where'];
        if(!empty($this->alias['group'])) $this->sql .= ' group by ' . $this->alias['group'];
        if(!empty($this->alias['order'])) $this->sql .= ' order by ' . $this->alias['order'];
        if(!empty($this->alias['limit'])) $this->sql .= ' limit ' . $this->alias['limit'];
    }
    //解析添加sql语句
    public function ParseAddSql()
    {
        $this->sql = 'insert into ';
        if( empty( $this->alias['table'] ) ){
            throw new \exception("请用table子句设置添加表");
        }else{
            $this->sql .= $this->alias['table'] . ' set ';
        }
        return $this->sql;
    }
    //解析更新sql语句
    public function ParseUpdateSql()
    {
        $this->sql = 'update ';
        if(empty( $this->alias['table'])){
            throw new \exception("请用table子句设置修改表");
        }else{
            $this->sql .= $this->alias['table'] . ' set ';
        }
        if(empty( $this->alias['where'])) throw new \exception("更新语句必须有where子句指定条件");
        return $this->sql;
    }
    //解析删除sql语句
    public function ParseDeleteSql()
    {
        $this->sql = 'delete from ';
        if(empty( $this->alias['table'])){
            throw new \exception("请用table子句设置删除表");
        }else{
            $this->sql .= $this->alias['table'];
        }
        if(empty($this->alias['where'])) throw new \exception("删除语句必须有where子句指定条件");
        $this->sql .= ' where ' . $this->alias['where'];
        return $this->sql;
    }


    //执行sql语句
    public function query($sql){
        return $this->querySql($sql);
    }
    //执行SQL
    public function querySql($sql, $query=true){
        $this->_resetAlias();
        $sql = str_replace(["'##","##'"], '', $sql);
        //不执行,只输出SQL语句
        if($query == false) return $sql;
        //执行
        $queryBuild = new QueryBuilder();
        $queryBuild->raw($sql);
        return DbManager::getInstance()->query($queryBuild, true, 'mysql')->toArray();
    }

    public function __get($name)
    {
        return $this->getData()[$name];
    }
    
    //设置缓存
    private function _setCache( $sql ){
        $cache_timeout = isset($this->alias['cache_timeout']) ? $this->alias['cache_timeout'] : null;
        $cache_key = isset($this->alias['cache_key']) ? $this->alias['cache_key'] : md5( $sql );
        $this->_resetAlias();
        
        $cache_key = $this->prefix_cache.$cache_key;
        $cache_res = Cache::get($cache_key);
        if(!$cache_timeout){
            $res = $this->querySql( $sql );
        } else {
            $res = $cache_res;
            if(!$cache_res) {
                $res = $this->querySql( $sql );
                Cache::set($cache_key, $res, $cache_key);
            }
        }
        return $res;
    }
    //设置表名
    public function _setTable( $table ){
        $this->alias['table'] = $this->prefix.$table;
        return $this;
    }
    //重置alias
    private function _resetAlias(){
        $this->alias = null;
        return true;
    }
    //获取表名
    static function getTable( $table ){
        return self::$prefix.$table;
    }

    /*
    public function offsetExists($offset)
    {
        if( !isset( $this->getData()[$offset] ) ){
            return NULL;
        }
    }
    public function offsetGet($offset)
    {
        return $this->getData()[$offset];
    }
    public function offsetSet($offset, $value)
    {
        return $this->data[$offset] = $value;
    }
    public function offsetUnset($offset)
    {
        unset( $this->data[$offset] );
    }
    */

}


/*
$orm = new MyOrm();
//查询语句
$res = $orm->table('user')->order('id desc')->select();
$res = $orm->table('user')->where("name='test'")->order('id desc')->select();
$res = $orm->table('user')->where(['id' => 1])->order('id desc')->find();
$res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit(2)->select();
$res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit('2,2')->select();

//你可以这样处理数据
foreach( $res as $key=>$vo ){
    echo $vo->name . '<br/>';
}
//也可以这样处理
foreach( $res as $key=>$vo ){
    echo $vo['name'] . '<br/>';
}
//还可以这样
foreach( $res as $key=>$vo ){
    print_r( $vo->getData() ) . '<br/>';
}
//添加数据
$data = [
    'name' => 'test1',
    'age' => 20,
    'password' => '21232f297a57a5a743894a0e4a801fc3',
    'salt' => 'domain'
];
$res = $orm->table('user')->insert( $data );
//更新数据
$res = $orm->table('user')->where(['id' => 4])->update( ['name' => 'sdfdsfdsd', 'salt' => '111'] );
//删除数据
$res = $orm->table('user')->where(['id' => 7, 'id' => 6])->delete();
//获取执行的sql语句
echo $orm->getLastSql();
var_dump($res);
*/